import React, { useCallback, useEffect, useState } from 'react';
import { Card, Empty, Spin, Table, Tooltip, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { DuplicationGroupDTO, DuplicationLocationDTO, getTopDuplicationGroups } from '../../../services/statistics';
import { buildGitLabFileLink, convertSshToHttp, formatRelativePath as formatRelativePathUtil } from '../../../utils/gitUrlUtils';

interface CodeDuplicationTableProps {
  unitId: string;
  gitRepoUrl?: string;
  currentBranch?: string;
  containerStyle?: React.CSSProperties;
}

const DEFAULT_BRANCH = 'master';

const CodeDuplicationTable: React.FC<CodeDuplicationTableProps> = ({
  unitId,
  gitRepoUrl,
  currentBranch = DEFAULT_BRANCH,
  containerStyle
}) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<DuplicationGroupDTO[]>([]);

  const resolveResponseData = (response: any): DuplicationGroupDTO[] => {
    if (!response) {
      return [];
    }
    if (Array.isArray(response)) {
      return response;
    }
    if (typeof response === 'object' && 'code' in response) {
      if (response.code === 0 && Array.isArray(response.data)) {
        return response.data;
      }
      if (response.code !== 0) {
        message.error(response.msg || '获取代码重复详情失败');
      }
    }
    return [];
  };

  const loadData = useCallback(async () => {
    if (!unitId) {
      return;
    }
    setLoading(true);
    try {
      const response = await getTopDuplicationGroups(unitId, 10);
      const groups = resolveResponseData(response);
      setDataSource(groups || []);
    } catch (error) {
      console.error('加载代码重复详情失败:', error);
      message.error('加载代码重复详情失败');
      setDataSource([]);
    } finally {
      setLoading(false);
    }
  }, [unitId]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const repoInfo = gitRepoUrl ? convertSshToHttp(gitRepoUrl) : null;
  const repoName = repoInfo?.repo || '';

  // 使用公共的路径格式化函数
  const formatRelativePath = (filePath: string) => {
    return formatRelativePathUtil(filePath, repoName);
  };

  const truncatePath = (path: string, maxLength: number = 80) => {
    if (!path) {
      return '';
    }
    if (path.length <= maxLength) {
      return path;
    }
    return `...${path.slice(-maxLength)}`;
  };

  const formatLineRange = (startLine?: number, endLine?: number) => {
    if (!startLine) {
      return '';
    }
    if (!endLine || endLine === startLine) {
      return `L${startLine}`;
    }
    return `L${startLine}-${endLine}`;
  };

  const buildLocationLink = (location: DuplicationLocationDTO) => {
    if (!gitRepoUrl) {
      return '';
    }
    const relativePath = formatRelativePath(location.filePath);
    const linkPath = relativePath || location.filePath.replace(/^[a-zA-Z]:[\\/]/, '').replace(/^\/+/, '');
    return buildGitLabFileLink(
      gitRepoUrl,
      currentBranch || DEFAULT_BRANCH,
      linkPath,
      location.startLine,
      location.endLine
    );
  };

  const renderLocationCell = (record: DuplicationGroupDTO) => {
    const locations = record.locations || [];
    if (locations.length === 0) {
      return <span style={{ color: '#999' }}>-</span>;
    }

    const tooltipContent = (
      <div style={{ maxWidth: '600px', padding: '4px' }}>
        {locations.map((location, idx) => {
          const relativePath = formatRelativePath(location.filePath);
          const range = formatLineRange(location.startLine, location.endLine);
          const link = buildLocationLink(location);

          return (
            <div key={`${location.filePath}-${idx}`} style={{ marginBottom: idx < locations.length - 1 ? '8px' : 0 }}>
              {link ? (
                <a
                  href={link}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    color: '#1890ff',
                    textDecoration: 'none',
                    fontSize: '12px',
                    wordBreak: 'break-all'
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.textDecoration = 'underline'}
                  onMouseLeave={(e) => e.currentTarget.style.textDecoration = 'none'}
                >
                  {relativePath} <span style={{ color: '#8c8c8c' }}>({range})</span>
                </a>
              ) : (
                <span style={{ color: '#262626', fontSize: '12px', wordBreak: 'break-all' }}>
                  {relativePath} <span style={{ color: '#8c8c8c' }}>({range})</span>
                </span>
              )}
            </div>
          );
        })}
      </div>
    );

    return (
      <Tooltip
        title={tooltipContent}
        placement="topLeft"
        overlayStyle={{ maxWidth: '650px' }}
        overlayInnerStyle={{
          backgroundColor: '#fff',
          boxShadow: '0 4px 16px rgba(0,0,0,0.12)',
          borderRadius: '6px',
          padding: '12px'
        }}
        color="#fff"
      >
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', alignItems: 'center' }}>
          {locations.slice(0, 2).map((location, idx) => {
            const relativePath = formatRelativePath(location.filePath);
            const fileName = relativePath.split('/').pop() || relativePath;
            const range = formatLineRange(location.startLine, location.endLine);
            const link = buildLocationLink(location);

            return (
              <React.Fragment key={`${location.filePath}-${idx}`}>
                {link ? (
                  <a
                    href={link}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{
                      color: '#1890ff',
                      textDecoration: 'none',
                      fontSize: '12px',
                      fontFamily: 'Monaco, Consolas, monospace',
                      whiteSpace: 'nowrap'
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.textDecoration = 'underline'}
                    onMouseLeave={(e) => e.currentTarget.style.textDecoration = 'none'}
                  >
                    {fileName} <span style={{ color: '#8c8c8c' }}>({range})</span>
                  </a>
                ) : (
                  <span style={{
                    color: '#262626',
                    fontSize: '12px',
                    fontFamily: 'Monaco, Consolas, monospace',
                    whiteSpace: 'nowrap'
                  }}>
                    {fileName} <span style={{ color: '#8c8c8c' }}>({range})</span>
                  </span>
                )}
                {idx < Math.min(locations.length, 2) - 1 && (
                  <span style={{ color: '#d9d9d9', margin: '0 4px' }}>|</span>
                )}
              </React.Fragment>
            );
          })}
          {locations.length > 2 && (
            <span style={{
              color: '#1890ff',
              fontSize: '12px',
              fontWeight: '500',
              marginLeft: '4px'
            }}>
              +{locations.length - 2}
            </span>
          )}
        </div>
      </Tooltip>
    );
  };

  const columns: ColumnsType<DuplicationGroupDTO> = [
    {
      title: '排名',
      key: 'rank',
      width: 70,
      align: 'center',
      render: (_: any, __: DuplicationGroupDTO, index: number) => index + 1
    },
    {
      title: '重复行数',
      dataIndex: 'lines',
      key: 'lines',
      width: 110,
      sorter: (a, b) => (a.lines || 0) - (b.lines || 0)
    },
    {
      title: '重复次数',
      dataIndex: 'occurrences',
      key: 'occurrences',
      width: 110
    },
    {
      title: '涉及文件',
      key: 'locations',
      render: (_: any, record: DuplicationGroupDTO) => renderLocationCell(record)
    }
  ];

  const hasData = dataSource && dataSource.length > 0;
  const cardStyle: React.CSSProperties = { marginTop: 16, height: '100%', ...containerStyle };

  return (
    <Card
      title="代码重复详情 (TOP10)"
      style={cardStyle}
      bodyStyle={{ padding: hasData ? 0 : 24 }}
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: '24px 0' }}>
          <Spin />
        </div>
      ) : hasData ? (
        <Table
          columns={columns}
          dataSource={dataSource}
          pagination={false}
          rowKey="duplicationGroupId"
          size="small"
        />
      ) : (
        <div style={{ padding: '24px 0' }}>
          <Empty description="暂无重复代码数据" />
        </div>
      )}
    </Card>
  );
};

export default CodeDuplicationTable;
